<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
        <el-row :gutter="20">
          <el-col :md="6" :sm="12">
            <el-form-item label="学生编号" prop="studentNo">
              <el-input
                v-model="queryParams.studentNo"
                placeholder="请输入学生编号"
                clearable
                prefix-icon="el-icon-postcard"
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="学生姓名" prop="studentName">
              <el-input
                v-model="queryParams.studentName"
                placeholder="请输入学生姓名"
                clearable
                prefix-icon="el-icon-user"
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="入学年份" prop="enrollmentYear">
              <el-date-picker
                v-model="queryParams.enrollmentYear"
                type="year"
                placeholder="选择入学年份"
                value-format="yyyy"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="12">
            <el-form-item label="毕业年份" prop="graduateYear">
              <el-date-picker
                v-model="queryParams.graduateYear"
                type="year"
                placeholder="选择毕业年份"
                value-format="yyyy"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['entrance:student:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['entrance:student:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['entrance:student:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-price-tag"
            size="mini"
            :disabled="single"
            @click="handleTagSet"
            v-hasPermi="['entrance:student:tag']"
          >设置标签
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <el-table 
        v-loading="loading" 
        :data="studentList" 
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: 'bold'}"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" width="60" />
        <el-table-column label="登录用户" prop="userName" :show-overflow-tooltip="true" width="100" />
        <el-table-column label="学生编号" prop="studentNo" :show-overflow-tooltip="true" width="120" />
        <el-table-column label="学生姓名" prop="studentName" :show-overflow-tooltip="true" width="100">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.studentName" placement="top">
              <span>
                <i class="el-icon-user" style="margin-right: 5px; color: #409EFF;"></i>
                {{ scope.row.studentName }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="性别" :show-overflow-tooltip="true" width="60" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.sex == 'MAN' ? 'primary' : 'danger'">
              {{ scope.row.sex == "MAN" ? "男" : scope.row.sex == "WOMEN" ? "女" : "未知" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入学年份" prop="enrollmentYear" :show-overflow-tooltip="true" width="100" align="center" />
        <el-table-column label="毕业年份" prop="graduateYear" :show-overflow-tooltip="true" width="100" align="center" />
        <el-table-column label="高考成绩" prop="achievement" :show-overflow-tooltip="true" width="100" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="success" v-if="scope.row.achievement">
              {{ scope.row.achievement }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="学生标签" prop="tagNameText" :show-overflow-tooltip="true" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.tagNameText">
              <el-tag 
                v-for="(tagName, index) in scope.row.tagNameText.split(',')" 
                :key="index" 
                size="mini" 
                type="info" 
                effect="plain"
                class="tag-item"
              >
                {{ tagName }}
              </el-tag>
            </div>
            <span v-else>无标签</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdTime" width="160">
          <template slot-scope="scope">
            <i class="el-icon-time" style="margin-right: 5px; color: #909399;"></i>
            <span>{{ parseTime(scope.row.createdTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope" v-if="scope.row.id !== 0">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleUpdate(scope.row)"
              v-hasPermi="['entrance:student:edit']"
              title="修改"
            />
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.row)"
              v-hasPermi="['entrance:student:remove']"
              title="删除"
            />
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-price-tag"
              circle
              @click="handleTagSet(scope.row)"
              v-hasPermi="['entrance:student:tag']"
              title="设置标签"
            />
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改学生配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学生编号" prop="studentNo">
              <el-input v-model="form.studentNo" placeholder="请输入学生编号" prefix-icon="el-icon-postcard" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生名称" prop="studentName">
              <el-input v-model="form.studentName" placeholder="请输入学生名称" prefix-icon="el-icon-user" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户账号,用来绑定登录用户" prefix-icon="el-icon-user-solid" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别" clearable style="width: 100%">
                <el-option
                  v-for="(item, index) in sexSelectOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value == 'MAN' ? '男' : '女' }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学年份" prop="enrollmentYear">
              <el-date-picker
                v-model="form.enrollmentYear"
                type="year"
                placeholder="选择入学年份"
                value-format="yyyy"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业年份" prop="graduateYear">
              <el-date-picker
                v-model="form.graduateYear"
                type="year"
                placeholder="选择毕业年份"
                value-format="yyyy"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高考成绩" prop="achievement">
              <el-input-number 
                v-model="form.achievement" 
                :precision="0" 
                :step="1" 
                :min="0" 
                :max="750" 
                placeholder="请输入高考成绩"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 标签  -->
    <el-dialog :title="tagTitle" :visible.sync="tagOpen" width="500px" append-to-body>
      <div class="tag-container">
        <el-tag
          v-for="tag in tagNames"
          :key="tag"
          closable
          effect="dark"
          class="student-tag"
          @close="handleTagClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="tagName"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleTagInputConfirm"
          @blur="handleTagInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" icon="el-icon-plus" @click="showTagInput">添加标签</el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bindTags">确 定</el-button>
        <el-button @click="tagOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, addStudent, updateStudent, getStudent, delStudent } from "@/api/entrance/student";
import { getTags, bindTags } from "@/api/entrance/tag";

export default {
  name: "Student",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentNo: undefined,
        studentName: undefined,
        enrollmentYear: undefined,
        graduateYear: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        studentNo: [
          { required: true, message: "学生编号不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户账号不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        enrollmentYear: [
          { required: true, message: "入学年份不能为空", trigger: "blur" }
        ],
        graduateYear: [
          { required: true, message: "毕业年份不能为空", trigger: "blur" }
        ]
      },
      //性别下拉框选项
      sexSelectOptions: [{
        value: 'MAN',
        label: '男'
      }, {
        value: 'WOMEN',
        label: '女'
      }],
      //标签属性
      tagOpen: false,
      tagTitle: '',
      inputVisible: false,
      tagNames: [],
      tagName: '',
      tagType: 'STUDENT',
      bindTagId: undefined
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(
        response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      ).catch(() => {
        this.loading = false;
        this.$message.error("获取学生列表失败");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        studentNo: undefined,
        studentName: undefined,
        userName: undefined,
        enrollmentYear: undefined,
        graduateYear: undefined,
        sex: undefined,
        achievement: undefined
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const studentId = row.id || this.ids
      getStudent(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateStudent(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$message.error("修改失败");
            });
          } else {
            addStudent(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$message.error("新增失败");
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.id || this.ids;
      this.$confirm('是否确认删除学生ID为"' + studentIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delStudent(studentIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    /** 设置标签*/
    handleTagSet(row) {
      const relId = row.id || this.ids
      getTags(this.tagType, relId).then(response => {
        this.tagOpen = true;
        this.tagTitle = "添加标签（用于志愿填报测评）";
        this.tagNames = response.data.tagNames;
        this.bindTagId = response.data.relId;
      });
    },
    /** 删除标签*/
    handleTagClose(tag) {
      this.tagNames.splice(this.tagNames.indexOf(tag), 1);
    },
    /** 展示标签输入框*/
    showTagInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    /** 标签输入确认*/
    handleTagInputConfirm() {
      let tagName = this.tagName;
      if (tagName) {
        this.tagNames.push(tagName);
      }
      this.inputVisible = false;
      this.tagName = '';
    },
    /** 绑定标签*/
    bindTags: function () {
      let tagData = {
        relId: this.bindTagId,
        tagType: this.tagType,
        tagNames: this.tagNames
      }
      bindTags(tagData).then(response => {
        this.$message.success("设置成功");
        //重置标签数据
        this.tagOpen = false;
        this.tagNames = [];
        this.tagName = '';
        this.bindTagId = undefined;
        this.getList();
      }).catch(() => {
        this.$message.error("设置失败");
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-card,
  .action-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 5px;
    
    ::v-deep .el-card__header {
      padding: 12px 20px;
      font-weight: bold;
    }
    
    ::v-deep .el-card__body {
      padding: 15px 20px;
    }
  }
  
  .tag-item {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  
  .input-new-tag {
    width: 150px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  
  .tag-container {
    padding: 10px;
    min-height: 100px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
    background-color: #f9f9f9;
  }
  
  .student-tag {
    margin: 5px;
  }
  
  ::v-deep .el-table {
    .el-button--mini.is-circle {
      padding: 7px;
    }
    
    th {
      background-color: #f5f7fa !important;
    }
  }
}
</style>
